package visualization;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;


@SuppressWarnings("serial")
/**
 * This class is the super class for all visualizations. A visualization extends a JPanel and 
 * will properly represent itself when painted.All visualizations must have a title, 
 * and be able to randomize the colors used in their representation.
 * @author Ben Schwab
 *
 */
public abstract class Visualization extends JPanel implements Runnable {

    private static final Dimension DEFAULT_SIZE = new Dimension(1000, 1000);
    private static final int FPS = 5;
    private static final int DELAY = 1000 / FPS;

    private Dimension myDimension;


    /**
     * 
     * @param dimension size of the visualization
     */
    public Visualization (Dimension dimension) {
        myDimension = dimension;
        this.setSize(myDimension);
        this.setPreferredSize(myDimension);
    }

    /**
     * 
     * @return the new Visualization with randomized colors
     */
    public abstract Visualization randomizeColors ();

    /**
     * 
     * @return returns the default size of a visualization
     */
    public static Dimension getDefaultSize () {
        return DEFAULT_SIZE;
    }

    /**
     * Clears the last draw visualization
     * @param pen Graphics object being drawn to
     */
    public void paintComponent (Graphics pen) {
        pen.setColor(Color.WHITE);
        pen.fillRect(0, 0, this.getWidth(), this.getHeight());
    };

    /**
     * 
     * @param title title to set for the visualization
     */
    public abstract void setTitle (String title);

    /**
     * 
     * @return return the size of the visualization
     */
    public Dimension getDimension () {
        return myDimension;
    }

    /**
     * Start the animation for a visualization if applicable.
     */
    @Override
    public void run () {
        long beforeTime;
        long timeDifference;
        long sleep;
        beforeTime = System.currentTimeMillis();
        while (true) {
            repaint();
            timeDifference = System.currentTimeMillis() - beforeTime;
            sleep = DELAY - timeDifference;
            if (sleep < 0) {
                sleep = 2;
            }
            try {
                Thread.sleep(sleep);
            }
            catch (InterruptedException e) {
                System.out.println("interrupted");
            }
            beforeTime = System.currentTimeMillis();
        }

    }
}
